package com.woniuxy.yygh.hsop.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.yygh.common.result.Result;
import com.woniuxy.yygh.hsop.mapper.UserAdminMapper;
import com.woniuxy.yygh.hsop.service.UserAdminService;
import com.woniuxy.yygh.model.hosp.UserAdmin;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 管理员接口实现类
 * <P> Date: 2022/3/13:18:47
 * <P> Description:
 */
@Service
public class UserAdminServiceImpl
        extends ServiceImpl<UserAdminMapper, UserAdmin>
        implements UserAdminService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result findByAccount(UserAdmin userAdmin) {

        if (userAdmin.getCodeToken() != null) {
            String code = (String) redisTemplate.opsForValue().get(userAdmin.getCodeToken());
            if (userAdmin.getCode() == null || !code.equals(userAdmin.getCode())) {
                return Result.fail().message("验证码错误");
            }
        }


        QueryWrapper<UserAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("account", userAdmin.getAccount());

        UserAdmin newUser = baseMapper.selectOne(wrapper);
        if (newUser == null) {
            return Result.fail().message("账号错误");
        }
        if (!newUser.getPassword().equals(userAdmin.getPassword())) {
            return Result.fail().message("密码错误");
        }

        String sb = newUser.getAccount() +
                newUser.getPassword();
        String intern = sb.intern();
        redisTemplate.opsForValue().set(intern, newUser);
        redisTemplate.expire(intern, 100, TimeUnit.MINUTES);

        return Result.ok(newUser);
    }

    @Override
    public Result updateUserAdmin(UserAdmin userAdmin) {

        String sb = userAdmin.getAccount() +
                userAdmin.getPassword();
        String intern = sb.intern();
        int i = baseMapper.updateById(userAdmin);

        redisTemplate.delete(intern);
        if (i > 0) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }
}
